<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="-定时任务 -Quartz,">










<meta name="description" content="quartz主要接口 Scheduler调度器接口 JobDetail job描述 Trigger触发器 Job 具体的job 各种监听器 JobListener TriggerListener SchedulerListener   一个JobDetail包括一个job 其可以绑定多个触发器 ，然后交给调度器调度执行。  基本使用1234567891011121314151617181920//">
<meta name="keywords" content="-定时任务 -Quartz">
<meta property="og:type" content="article">
<meta property="og:title" content="Quartz集群">
<meta property="og:url" content="https://zhangzt123.github.io/2020/09/01/2020-09-01-Quartz集群/index.html">
<meta property="og:site_name">
<meta property="og:description" content="quartz主要接口 Scheduler调度器接口 JobDetail job描述 Trigger触发器 Job 具体的job 各种监听器 JobListener TriggerListener SchedulerListener   一个JobDetail包括一个job 其可以绑定多个触发器 ，然后交给调度器调度执行。  基本使用1234567891011121314151617181920//">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-09-30T08:05:44.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Quartz集群">
<meta name="twitter:description" content="quartz主要接口 Scheduler调度器接口 JobDetail job描述 Trigger触发器 Job 具体的job 各种监听器 JobListener TriggerListener SchedulerListener   一个JobDetail包括一个job 其可以绑定多个触发器 ，然后交给调度器调度执行。  基本使用1234567891011121314151617181920//">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zhangzt123.github.io/2020/09/01/2020-09-01-Quartz集群/">





  <title>Quartz集群 | </title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title"></span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zhangzt123.github.io/2020/09/01/2020-09-01-Quartz集群/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="MR.zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content>
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Quartz集群</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-09-01T11:49:29+08:00">
                2020-09-01
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2020-09-30T16:05:44+08:00">
                2020-09-30
              </time>
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/spring/" itemprop="url" rel="index">
                    <span itemprop="name">-spring</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="quartz主要接口"><a href="#quartz主要接口" class="headerlink" title="quartz主要接口"></a>quartz主要接口</h2><ul>
<li>Scheduler调度器接口</li>
<li>JobDetail job描述</li>
<li>Trigger触发器</li>
<li>Job 具体的job</li>
<li>各种监听器 JobListener TriggerListener SchedulerListener</li>
</ul>
<blockquote>
<p>一个JobDetail包括一个job 其可以绑定多个触发器 ，然后交给调度器调度执行。</p>
</blockquote>
<h2 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//通过调度工厂创建调度器</span></span><br><span class="line">SchedulerFactory schedulerFactory = <span class="keyword">new</span> StdSchedulerFactory();</span><br><span class="line">        Scheduler scheduler = schedulerFactory.getScheduler();</span><br><span class="line">        <span class="comment">//添加监听器 可以为指定job 触发器 通过Matcher比较器接口</span></span><br><span class="line">        <span class="comment">//scheduler.getListenerManager().addJobListener();</span></span><br><span class="line">        <span class="comment">//scheduler.getListenerManager().addTriggerListener();</span></span><br><span class="line">        <span class="comment">//scheduler.getListenerManager().addSchedulerListener();</span></span><br><span class="line">        <span class="comment">//通过Myjob创建jobDetail Myjob实现Job接口</span></span><br><span class="line">        <span class="comment">//主要job实现在execute(JobExecutionContext context)方法</span></span><br><span class="line">        JobDetail jobDetail = JobBuilder.newJob(Myjob.class).withIdentity(<span class="string">"jobname"</span>,<span class="string">"jobgroup"</span>).requestRecovery()</span><br><span class="line">                .build();</span><br><span class="line">        <span class="comment">//创建触发器 </span></span><br><span class="line">        Trigger trigger =TriggerBuilder.newTrigger()</span><br><span class="line">        .withIdentity(<span class="string">"triggername"</span>,<span class="string">"triggergroup"</span>)</span><br><span class="line">                .withSchedule(CronScheduleBuilder.cronSchedule(<span class="string">"0 * * * * ?"</span>))</span><br><span class="line">                .startNow()<span class="comment">//立即启动</span></span><br><span class="line">                .build();</span><br><span class="line">        <span class="comment">//绑定 job和触发器</span></span><br><span class="line">        scheduler.scheduleJob(jobDetail,trigger);</span><br><span class="line">        scheduler.start();<span class="comment">//启动所有job  可以在创建jobDetail 和trigger 之前启动</span></span><br></pre></td></tr></table></figure>

<h2 id="quartz集群"><a href="#quartz集群" class="headerlink" title="quartz集群"></a>quartz集群</h2><blockquote>
<p>quartz实现集群的方式时通过数据库锁的方式，其隶属于悲观锁，主要通过其配置文件来初始化调度器，其配置文件名为quartz.properties ，quartz默认使用StdScheduler的实现，其中包括大量的配置，其中部分配置如下</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">#基础配置</span><br><span class="line">#指定实例名 默认QuartzScheduler</span><br><span class="line">org.quartz.scheduler.instanceName =</span><br><span class="line">#集群模式使用AUTO 全大写</span><br><span class="line">org.quartz.scheduler.instanceId= AUTO</span><br><span class="line">#指定实例id生成器</span><br><span class="line">#org.quartz.scheduler.instanceIdGenerator.class=org.quartz.simpl.SimpleInstanceIdGenerator</span><br><span class="line">#org.quartz.scheduler.threadName =</span><br><span class="line">#org.quartz.scheduler.makeSchedulerThreadDaemon=true</span><br><span class="line">#org.quartz.scheduler.threadsInheritContextClassLoaderOfInitializer=</span><br><span class="line"># 线程配置</span><br><span class="line">org.quartz.threadPool.class =org.quartz.simpl.SimpleThreadPool</span><br><span class="line"># 线程数大于0</span><br><span class="line">org.quartz.threadPool.threadCount = 10</span><br><span class="line">#线程优先级</span><br><span class="line">org.quartz.threadPool.threadPriority=5</span><br><span class="line">#job存储 默认使用RAMJobStore 内存存储 集群默认使用JobStoreTX  jdbc存储</span><br><span class="line">#jobstore</span><br><span class="line">org.quartz.jobStore.class =org.quartz.impl.jdbcjobstore.JobStoreTX</span><br><span class="line">#数据源名称 必须</span><br><span class="line">org.quartz.jobStore.DataSource=mydatasource</span><br><span class="line">#驱动代理类 必须</span><br><span class="line">org.quartz.jobStore.DriverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate</span><br><span class="line">org.quartz.jobStore.useProperties=true</span><br><span class="line">#集群模式必须</span><br><span class="line">org.quartz.jobStore.isClustered=true</span><br><span class="line"></span><br><span class="line">#datasource数据源配置  也可使用jndi</span><br><span class="line">org.quartz.dataSource=mydatasource</span><br><span class="line">org.quartz.dataSource.mydatasource.driver=com.mysql.jdbc.Driver</span><br><span class="line">org.quartz.dataSource.mydatasource.URL=jdbc:mysql://192.168.118.134:3306/quartz?characterEncoding=utf-8&amp;useSSL=false</span><br><span class="line">org.quartz.dataSource.mydatasource.user=</span><br><span class="line">org.quartz.dataSource.mydatasource.password=</span><br><span class="line">org.quartz.dataSource.mydatasource.maxConnections=10</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#org.quartz.dataSource.mydatasource.connectionProvider.class=com.myquartz.config.MyConnectionProvider</span><br><span class="line"></span><br><span class="line">        </span><br><span class="line">###更多配置 stdSchedulerFactory</span><br></pre></td></tr></table></figure>

<blockquote>
<p>调度工厂拥有两种构造器，通过properties 或者filepath 的方式加载配置文件，再通过配置文件创建调度器。</p>
</blockquote>
<h2 id="quartz-数据库表"><a href="#quartz-数据库表" class="headerlink" title="quartz 数据库表"></a>quartz 数据库表</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">table qrtz_calendars;<span class="comment">--存储calendars信息</span></span><br><span class="line">table qrtz_fired_triggers;<span class="comment">--存储已触发的触发器的状态和相关job信息</span></span><br><span class="line">table qrtz_blob_triggers;<span class="comment">--属于blob类型存储的自定义类型触发器</span></span><br><span class="line">table qrtz_cron_triggers;<span class="comment">--存储cron_triggers的触发器</span></span><br><span class="line">table qrtz_simple_triggers;<span class="comment">--存储简单的触发器</span></span><br><span class="line">table qrtz_simprop_triggers;<span class="comment">--存储CalendarIntervalTrigger和DailyTimeIntervalTrigger两种类型触发器</span></span><br><span class="line">table qrtz_triggers;<span class="comment">--存储触发器信息</span></span><br><span class="line">table qrtz_job_details;<span class="comment">-- 存储job信息</span></span><br><span class="line">table qrtz_paused_trigger_grps;<span class="comment">-- 存储已暂停的触发器</span></span><br><span class="line">table qrtz_locks;<span class="comment">--存储锁信息</span></span><br><span class="line">table qrtz_scheduler_state;<span class="comment">--存储调度器状态</span></span><br></pre></td></tr></table></figure>

<h2 id="spring集成quartz"><a href="#spring集成quartz" class="headerlink" title="spring集成quartz"></a>spring集成quartz</h2><blockquote>
<p>spring中已经集成了quartz ,其源码位置在spring-context 和 spring-context-support 下的scheduling包下，在传统的xml配置方式中，有个关键的类SchedulerFactoryBean，是作为spring和quartz连接的桥梁，在springboot中再次升级，采用自动配置的方式，所采用的类为QuartzAutoConfiguration，万变不离其宗，其中提供了关键了SchedulerFactoryBean的bean注入。</p>
</blockquote>
<h3 id="SchedulerFactoryBean"><a href="#SchedulerFactoryBean" class="headerlink" title="SchedulerFactoryBean"></a>SchedulerFactoryBean</h3><blockquote>
<p>SchedulerFactoryBean实现了InitializingBean ，其实现方法afterPropertiesSet即使关键中的关键，该方法默认会通过schedulerFactory创建一个stdscheduler，同时向stdscheduler中添加job ，触发器，以及监听器。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">		.......</span><br><span class="line">		<span class="keyword">this</span>.scheduler = prepareScheduler(prepareSchedulerFactory());</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			registerListeners();</span><br><span class="line">			registerJobsAndTriggers();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">			......</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">private</span> SchedulerFactory <span class="title">prepareSchedulerFactory</span><span class="params">()</span> <span class="keyword">throws</span> SchedulerException, IOException </span>&#123;</span><br><span class="line">		SchedulerFactory schedulerFactory = <span class="keyword">this</span>.schedulerFactory;</span><br><span class="line">		<span class="keyword">if</span> (schedulerFactory == <span class="keyword">null</span>) &#123;</span><br><span class="line">			schedulerFactory = BeanUtils.instantiateClass(<span class="keyword">this</span>.schedulerFactoryClass);</span><br><span class="line">...</span><br><span class="line">		<span class="keyword">return</span> schedulerFactory;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>

<h3 id="QuartzAutoConfiguration"><a href="#QuartzAutoConfiguration" class="headerlink" title="QuartzAutoConfiguration"></a>QuartzAutoConfiguration</h3><blockquote>
<p>QuartzAutoConfiguration类是一个自动配置类，在项目启动时，通过@EnableAutoConfiguration进行配置的加载，该类出现在spring.factories文件中。其头部包括大量注解，通过@EnableConfigurationProperties(QuartzProperties.class)可以将quartz的配置信息从application配置文件中加载进来。AutoConfigureAfter则表示该类需要在指定的几个类都自动配置完成之后再进行配置。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span>(proxyBeanMethods = <span class="keyword">false</span>)</span><br><span class="line"><span class="meta">@ConditionalOnClass</span>(&#123; Scheduler.class, SchedulerFactoryBean.class, PlatformTransactionManager.class &#125;)</span><br><span class="line"><span class="meta">@EnableConfigurationProperties</span>(QuartzProperties.class)</span><br><span class="line"><span class="meta">@AutoConfigureAfter</span>(&#123; DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,</span><br><span class="line">		LiquibaseAutoConfiguration.class, FlywayAutoConfiguration.class &#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>该类最为重要的是其中的quartzScheduler方法，其参数很多，具体如下,包括 几个重要的bean 其中有jobDetails，和 triggers 分别是任务和触发器的bean 表示该类方法还可将注册为bean的job和触发器 交由调度器调度 ，所以也可以直接将job和触发器注册为bean。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line">	<span class="meta">@ConditionalOnMissingBean</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> SchedulerFactoryBean <span class="title">quartzScheduler</span><span class="params">(QuartzProperties properties,</span></span></span><br><span class="line"><span class="function"><span class="params">			ObjectProvider&lt;SchedulerFactoryBeanCustomizer&gt; customizers, ObjectProvider&lt;JobDetail&gt; jobDetails,</span></span></span><br><span class="line"><span class="function"><span class="params">			Map&lt;String, Calendar&gt; calendars, ObjectProvider&lt;Trigger&gt; triggers, ApplicationContext applicationContext)</span></span></span><br></pre></td></tr></table></figure>

<h3 id="工具类"><a href="#工具类" class="headerlink" title="工具类"></a>工具类</h3><h4 id="application-yml"><a href="#application-yml" class="headerlink" title="application.yml"></a>application.yml</h4><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line"><span class="attr">  quartz:</span></span><br><span class="line"><span class="attr">      schedulerName:</span> <span class="string">myscheduler</span></span><br><span class="line"><span class="attr">      autoStartup:</span> <span class="literal">true</span></span><br><span class="line"><span class="attr">      job-store-type:</span> <span class="string">JDBC</span></span><br><span class="line"><span class="comment">#      jdbc:</span></span><br><span class="line"><span class="comment">#          schema: classpath:org/quartz/impl/jdbcjobstore/tables_mysql.sql</span></span><br><span class="line"><span class="comment">#      initialize-schema: ALWAYS</span></span><br><span class="line"><span class="comment"># 可以用以添加quartz.properties有的配置</span></span><br><span class="line"><span class="attr">      properties:</span> </span><br><span class="line"><span class="attr">          org:</span></span><br><span class="line"><span class="attr">            quartz:</span></span><br><span class="line">				<span class="attr">scheduler:</span></span><br><span class="line"><span class="comment">#全大写</span></span><br><span class="line"><span class="attr">                    instanceId:</span> <span class="string">AUTO</span></span><br><span class="line"><span class="attr">                threadPool:</span></span><br><span class="line">                    <span class="string">class</span> <span class="string">:</span> <span class="string">org.quartz.simpl.SimpleThreadPool</span></span><br><span class="line">                    <span class="string">threadCount</span> <span class="string">:</span> <span class="number">10</span></span><br><span class="line"><span class="attr">                    threadPriority:</span> <span class="number">5</span></span><br><span class="line"><span class="attr">                jobStore:</span></span><br><span class="line"><span class="attr">                    isClustered:</span> <span class="literal">true</span></span><br></pre></td></tr></table></figure>

<h4 id="quartzMgr-java"><a href="#quartzMgr-java" class="headerlink" title="quartzMgr.java"></a>quartzMgr.java</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.myquartz.utils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.quartz.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * quartz 工具类</span></span><br><span class="line"><span class="comment"> * *Note: 一个job可以绑定多个触发器 一个触发器只能绑定一个job</span></span><br><span class="line"><span class="comment"> * 使用</span></span><br><span class="line"><span class="comment"> *  1.将该类注入通过QuartzMgr(Scheduler scheduler)实例化</span></span><br><span class="line"><span class="comment"> *  2.创建job createJob（...）</span></span><br><span class="line"><span class="comment"> *  3.绑定触发器 bindTrigger（....）</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> *  spring 注入</span></span><br><span class="line"><span class="comment"> *   <span class="doctag">@ConditionalOnClass</span>(value=&#123;SchedulerFactoryBean.class&#125;)</span></span><br><span class="line"><span class="comment"> *    <span class="doctag">@Bean</span></span></span><br><span class="line"><span class="comment"> *    public QuartzMgr quartzMgr(SchedulerFactoryBean quartzScheduler)&#123;</span></span><br><span class="line"><span class="comment"> *         QuartzMgr quartzMgr =new QuartzMgr(quartzScheduler.getScheduler());</span></span><br><span class="line"><span class="comment"> *         return quartzMgr;</span></span><br><span class="line"><span class="comment"> *    &#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">QuartzMgr</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span>  <span class="title">QuartzMgr</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Scheduler scheduler = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 初始化</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> scheduler</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span>  <span class="title">QuartzMgr</span><span class="params">(Scheduler scheduler)</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">this</span>.scheduler==<span class="keyword">null</span>)&#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (QuartzMgr.class)&#123;</span><br><span class="line">                <span class="keyword">if</span>(<span class="keyword">this</span>.scheduler==<span class="keyword">null</span>)&#123;</span><br><span class="line">                    <span class="keyword">this</span>.scheduler = scheduler;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 创建 job</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> jobKey job名称 组</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> job job执行class</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> jobdescription job描述</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> map job传入参数 可在job类中通过JobExecutionContext获得</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> SchedulerException</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> JobKey <span class="title">createJob</span><span class="params">(JobKey jobKey,Class job,String jobdescription,JobDataMap map)</span> <span class="keyword">throws</span> SchedulerException, ClassNotFoundException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(scheduler.checkExists(jobKey))&#123;</span><br><span class="line">            <span class="keyword">throw</span>  <span class="keyword">new</span> SchedulerException(jobKey.toString()+<span class="string">"该job已存在"</span>);</span><br><span class="line"><span class="comment">//            return jobKey;</span></span><br><span class="line">        &#125;</span><br><span class="line">       <span class="keyword">if</span>(!Job.class.isAssignableFrom(job))&#123;<span class="comment">//判断是Job的实现</span></span><br><span class="line">           <span class="keyword">throw</span>  <span class="keyword">new</span> SchedulerException(jobKey.toString()+<span class="string">"该Class不是一个Job实现"</span>);</span><br><span class="line">       &#125;</span><br><span class="line">        JobDetail jobDetail = JobBuilder.newJob()</span><br><span class="line">                .ofType(job)</span><br><span class="line">                .storeDurably(<span class="keyword">true</span>)<span class="comment">//无论是否关联trigger都存在</span></span><br><span class="line">                .withIdentity(jobKey)</span><br><span class="line">                .withDescription(jobdescription)</span><br><span class="line">                .requestRecovery(<span class="keyword">true</span>)<span class="comment">//调度失败请求重新调度</span></span><br><span class="line">                .setJobData(map)</span><br><span class="line">                .build();</span><br><span class="line">        scheduler.addJob(jobDetail,<span class="keyword">false</span>);</span><br><span class="line">        <span class="keyword">return</span> jobKey;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> DailyTimeIntervalScheduleBuilder</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> CronScheduleBuilder</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> CalendarIntervalScheduleBuilder</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> SimpleScheduleBuilder</span></span><br><span class="line"><span class="comment">     * job绑定一个新触发器</span></span><br><span class="line"><span class="comment">     * 一个job可以绑定多个触发器， 但是一个触发器只能绑定一个job</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> jobKey 已存在的job 或者 createJob()创建</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> triggerKey 触发器名称</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> map  参数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> schedBuilder</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> DailyTimeIntervalScheduleBuilder</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> CronScheduleBuilder</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> CalendarIntervalScheduleBuilder</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> SimpleScheduleBuilder</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> triggerdescription trigger描述</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> SchedulerException</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">bindTrigger</span><span class="params">(JobKey jobKey,TriggerKey triggerKey,JobDataMap map,ScheduleBuilder schedBuilder,String triggerdescription)</span> <span class="keyword">throws</span> SchedulerException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(scheduler.checkExists(triggerKey))&#123;</span><br><span class="line">            <span class="keyword">throw</span>  <span class="keyword">new</span> SchedulerException(triggerKey.toString()+<span class="string">"该触发器已存在"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(!scheduler.checkExists(jobKey))&#123;</span><br><span class="line">            <span class="keyword">throw</span>  <span class="keyword">new</span> SchedulerException(jobKey.toString()+<span class="string">"该job不存在"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();</span><br><span class="line">        triggerBuilder</span><br><span class="line">                .usingJobData(map)</span><br><span class="line">                .withIdentity(triggerKey)</span><br><span class="line">                .withSchedule(schedBuilder)<span class="comment">//设定出发时间</span></span><br><span class="line">                .withDescription(triggerdescription)</span><br><span class="line">                .forJob(jobKey)</span><br><span class="line">                .startNow();</span><br><span class="line">        Trigger trigger = triggerBuilder.build();</span><br><span class="line">        scheduler.scheduleJob(trigger);</span><br><span class="line"><span class="comment">//        return true;</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 更新触发时点</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateTrigger</span><span class="params">(TriggerKey oldtriggerKey,JobDataMap map,ScheduleBuilder schedBuilder,String triggerdescription)</span> <span class="keyword">throws</span> SchedulerException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>( !scheduler.checkExists(oldtriggerKey) )</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">throw</span>  <span class="keyword">new</span> SchedulerException(oldtriggerKey.toString()+<span class="string">"不存在"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        Trigger oldtrigger = scheduler.getTrigger(oldtriggerKey);</span><br><span class="line">        <span class="keyword">if</span> (oldtrigger==<span class="keyword">null</span>)&#123;</span><br><span class="line">            <span class="keyword">throw</span>  <span class="keyword">new</span> SchedulerException(oldtriggerKey.toString()+<span class="string">"不存在"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        JobKey jobKey = oldtrigger.getJobKey();</span><br><span class="line">        Trigger newTrigger = TriggerBuilder.newTrigger()</span><br><span class="line">                    .startNow()</span><br><span class="line">                    .usingJobData(map)</span><br><span class="line">                    .forJob(jobKey)</span><br><span class="line">                    .withIdentity(oldtriggerKey)</span><br><span class="line">                    .withSchedule(schedBuilder)</span><br><span class="line">                    .withDescription(triggerdescription)</span><br><span class="line">                    .build();</span><br><span class="line">        scheduler.rescheduleJob(oldtriggerKey,newTrigger);</span><br><span class="line"><span class="comment">//        return true;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 删除任务</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delScheduler</span><span class="params">(JobKey jobKey)</span> <span class="keyword">throws</span> SchedulerException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(!scheduler.checkExists(jobKey))&#123;</span><br><span class="line">            <span class="keyword">throw</span>  <span class="keyword">new</span> SchedulerException(<span class="string">"job"</span>+jobKey.toString()+<span class="string">"不存在"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        List&lt;TriggerKey&gt; lists =getTriggerKeysOfJob(jobKey);</span><br><span class="line">        <span class="keyword">for</span>(TriggerKey triggerKey : lists)&#123;</span><br><span class="line">            <span class="comment">//停止触发器</span></span><br><span class="line">            scheduler.pauseTrigger(triggerKey);</span><br><span class="line">            <span class="comment">//移除触发器</span></span><br><span class="line">            scheduler.unscheduleJob(triggerKey);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//删除任务</span></span><br><span class="line">        scheduler.deleteJob(jobKey);</span><br><span class="line">        <span class="comment">//return true;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 停止任务</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> jobKey</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> triggerKey</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">pauseScheduler</span><span class="params">(JobKey jobKey,TriggerKey triggerKey)</span> <span class="keyword">throws</span> SchedulerException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(!scheduler.checkExists(jobKey)|| !scheduler.checkExists(triggerKey))&#123;</span><br><span class="line">            <span class="keyword">throw</span>  <span class="keyword">new</span> SchedulerException(<span class="string">"触发器"</span>+triggerKey.toString()+<span class="string">"不存在或者job"</span>+jobKey.toString()+<span class="string">"不存在"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        scheduler.pauseTrigger(triggerKey);</span><br><span class="line">        scheduler.pauseJob(jobKey);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 恢复任务</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> jobKey</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> triggerKey</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">resumeScheduler</span><span class="params">(JobKey jobKey,TriggerKey triggerKey)</span> <span class="keyword">throws</span> SchedulerException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(!scheduler.checkExists(jobKey)|| !scheduler.checkExists(triggerKey))&#123;</span><br><span class="line">            <span class="keyword">throw</span>  <span class="keyword">new</span> SchedulerException(<span class="string">"触发器"</span>+triggerKey.toString()+<span class="string">"不存在或者job"</span>+jobKey.toString()+<span class="string">"不存在"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        scheduler.resumeJob(jobKey);</span><br><span class="line">        scheduler.resumeTrigger(triggerKey);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获得所有于该job绑定的触发器</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> jobKey</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;TriggerKey&gt; <span class="title">getTriggerKeysOfJob</span><span class="params">(JobKey jobKey)</span> <span class="keyword">throws</span> SchedulerException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(!scheduler.checkExists(jobKey))&#123;</span><br><span class="line">            <span class="keyword">throw</span>  <span class="keyword">new</span> SchedulerException(<span class="string">"job"</span>+jobKey.toString()+<span class="string">"不存在"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        List&lt;TriggerKey&gt; triggerKeys = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        List&lt;? extends Trigger&gt; triggers = scheduler.getTriggersOfJob(jobKey);</span><br><span class="line">        <span class="keyword">for</span> (Trigger t:triggers) &#123;</span><br><span class="line">            triggerKeys.add(t.getKey());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> triggerKeys;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获得触发器状态</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> triggerKey</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> NONE, NORMAL, PAUSED, COMPLETE, ERROR, BLOCKED</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> SchedulerException</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> Trigger.<span class="function">TriggerState <span class="title">getTriggerState</span><span class="params">(TriggerKey triggerKey)</span> <span class="keyword">throws</span> SchedulerException </span>&#123;</span><br><span class="line">        <span class="keyword">return</span>  scheduler.getTriggerState(triggerKey);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获得正在执行的job</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> SchedulerException</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span>  List&lt;JobKey&gt; <span class="title">getExectingJob</span><span class="params">()</span> <span class="keyword">throws</span> SchedulerException </span>&#123;</span><br><span class="line">        List&lt;JobKey&gt; jobKeys = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        List&lt;JobExecutionContext&gt; lists =scheduler.getCurrentlyExecutingJobs();</span><br><span class="line">        <span class="keyword">for</span>(JobExecutionContext jobExecutionContext : lists)&#123;</span><br><span class="line">            jobKeys.add(jobExecutionContext.getJobDetail().getKey());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> jobKeys;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    
+ <div style="text-align:center;color: #ccc;font-size:14px;">---------------- The End ----------------</div>
    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/定时任务-Quartz/" <i class="fa fa-tag"> -定时任务 -Quartz</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/08/18/2020-08-18-统一异常处理/" rel="next" title="spring统一异常处理">
                <i class="fa fa-chevron-left"></i> spring统一异常处理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/10/14/2020-10-14-Activiti工作流/" rel="prev" title="Activiti工作流">
                Activiti工作流 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">MR.zhang</p>
              <p class="site-description motion-element" itemprop="description">坚持是一种态度,每一分都值得</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">39</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#quartz主要接口"><span class="nav-number">1.</span> <span class="nav-text">quartz主要接口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基本使用"><span class="nav-number">2.</span> <span class="nav-text">基本使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#quartz集群"><span class="nav-number">3.</span> <span class="nav-text">quartz集群</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#quartz-数据库表"><span class="nav-number">4.</span> <span class="nav-text">quartz 数据库表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#spring集成quartz"><span class="nav-number">5.</span> <span class="nav-text">spring集成quartz</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#SchedulerFactoryBean"><span class="nav-number">5.1.</span> <span class="nav-text">SchedulerFactoryBean</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#QuartzAutoConfiguration"><span class="nav-number">5.2.</span> <span class="nav-text">QuartzAutoConfiguration</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#工具类"><span class="nav-number">5.3.</span> <span class="nav-text">工具类</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#application-yml"><span class="nav-number">5.3.1.</span> <span class="nav-text">application.yml</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#quartzMgr-java"><span class="nav-number">5.3.2.</span> <span class="nav-text">quartzMgr.java</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">MR.zhang</span>

  
</div>









        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
